import {Form, Input, Tooltip, Icon, Row, Col, Button} from 'antd';
import React from 'react';
import reqwest from 'reqwest';

const FormItem = Form.Item;

class RegistrationForm extends React.Component {
    state = {
        confirmDirty: false,
        // autoCompleteResult: [],
        sendEmailLoading: false,
        sendEmailCD: 0,
        sendEmailSuccess: false,
    };

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll({force: true}, (err, values) => {
            if (!err) {
                reqwest({
                    url: '/api/register',
                    method: 'post',
                    data: values,
                    success: (res) => {
                        if (res.error !== '') {
                            this.error = res.error;
                            this.props.form.validateFields(['email', 'captcha'], {force: true});
                        } else {
                            this.props.handleRegister(res.user);
                        }
                    }
                })
            }
        });
    };

    handleConfirmBlur = (e) => {
        const value = e.target.value;
        this.setState({confirmDirty: this.state.confirmDirty || !!value});
    };

    handleEmailChange = () => {
        if (this.error) {
            this.error.email = null;
        }
    };

    handleCaptchaChange = () => {
        if (this.error) {
            this.error.captcha = null;
        }
    };

    compareToFirstPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && value !== form.getFieldValue('password')) {
            callback('两次输入密码不一致!');
        } else {
            callback();
        }
    };

    validateToNextPassword = (rule, value, callback) => {
        const form = this.props.form;
        if (value && this.state.confirmDirty) {
            form.validateFields(['confirm'], {force: true});
        }
        callback();
    };

    validateUserAlreadyExists = (rule, value, callback) => {
        if (this.error && this.error.email) {
            callback(this.error.email);
        }
        callback();
    };

    validateCaptcha = (rule, value, callback) => {
        if (this.error && this.error.captcha) {
            callback(this.error.captcha);
        }
        callback();
    };

    sendCaptcha = () => {
        this.props.form.validateFieldsAndScroll(['email'], {force: true}, (err) => {
            if (err) return;
            if (this.state.sendEmailCD === 0) {
                const form = this.props.form;
                this.setState({
                    sendEmailLoading: true,
                });
                reqwest({
                    url: '/api/captcha',
                    method: 'post',
                    data: {email: form.getFieldValue('email')},
                    success: (res) => {
                        if (res.error !== '') {
                            this.error = res.error;
                            this.props.form.validateFieldsAndScroll(['email'],{force:true});
                            this.setState({
                                sendEmailLoading: false,
                            })
                        } else {
                            this.setState({
                                sendEmailLoading: false,
                                sendEmailCD: 60,
                                sendEmailSuccess: true,
                            });
                            this.intervalID = setInterval(() => {
                                this.setState((prevState) => {
                                    if (prevState.sendEmailCD === 1) {
                                        clearInterval(this.intervalID);
                                    }
                                    return {
                                        sendEmailCD: prevState.sendEmailCD - 1
                                    }
                                })
                            }, 1000);
                        }
                    }
                })
            }
        });
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 8},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 16},
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 16,
                    offset: 8,
                },
            },
        };
        const sendEmailButton = (this.state.sendEmailCD === 0) ?
            <Button onClick={this.sendCaptcha} loading={this.state.sendEmailLoading}
                    disabled={this.state.sendEmailCD}>获取验证码</Button> :
            <Button disabled>{this.state.sendEmailCD}</Button>
        return (
            <Form onSubmit={this.handleSubmit}>
                <FormItem
                    {...formItemLayout}
                    label="邮箱"
                >
                    {getFieldDecorator('email', {
                        rules: [{
                            type: 'email', message: '请输入正确的邮箱!',
                        }, {
                            required: true, message: '请输入邮箱!',
                        }, {
                            validator: this.validateUserAlreadyExists,
                        }],
                    })(
                        <Input onChange={this.handleEmailChange}/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="密码"
                >
                    {getFieldDecorator('password', {
                        rules: [{
                            required: true, message: '请输入密码',
                        }, {
                            validator: this.validateToNextPassword,
                        }],
                    })(
                        <Input type="password"/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="再次输入密码"
                >
                    {getFieldDecorator('confirm', {
                        rules: [{
                            required: true, message: '请再次输入密码',
                        }, {
                            validator: this.compareToFirstPassword,
                        }],
                    })(
                        <Input type="password" onBlur={this.handleConfirmBlur}/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label={(
                        <span>
              昵称&nbsp;
                            <Tooltip title="你的昵称是什么？">
                <Icon type="question-circle-o"/>
              </Tooltip>
            </span>
                    )}
                >
                    {getFieldDecorator('nickname', {
                        rules: [{required: true, message: '请输入昵称！', whitespace: true}],
                    })(
                        <Input/>
                    )}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="验证码"
                    extra="请输入邮箱中的验证码！"
                >
                    <Row gutter={8}>
                        <Col span={12}>
                            {getFieldDecorator('captcha', {
                                rules: [
                                    {required: true, message: '请输入验证码！'},
                                    {validator: this.validateCaptcha}],
                            })(
                                <Input onChange={this.handleCaptchaChange}/>
                            )}
                        </Col>
                        <Col span={12}>
                            {sendEmailButton}
                        </Col>
                    </Row>
                </FormItem>
                <FormItem {...tailFormItemLayout}>
                    <Button type="primary" htmlType="submit">注册</Button>
                </FormItem>
            </Form>
        )
            ;
    }
}

const WrappedRegistrationForm = Form.create()(RegistrationForm);

export default WrappedRegistrationForm;